package com.platform.demo.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 全局拦截器，拦击之后分别判断请求的服务鉴权
 *  1、会话控制
 *  2、系统注册控制
 *  3、白名单请求控制
 * ClassName: ServiceInterceptor 
 */
@Service
public class ServiceInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("preHandle");       
        setCrossDomain(response);
        //获取session会话
        boolean sessFlag = true;
        //获取认证服务的验证结果
        boolean certFlag = true;
        //获取白名单服务的验证结果
        boolean urlFlag = true;
        
        if (sessFlag && certFlag && urlFlag) {
            return true;
        }
        //表示其中有验证不通过的情况，需要返回错误
        return false;
    }
    
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {
        logger.info("postHandle");
    }
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        logger.info("afterCompletion");
    }
    
    private void setCrossDomain(HttpServletResponse response){
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST,GET");
        response.addHeader("Access-Control-Allow-Credentials", "true");
    }
    
    
}
